﻿using System;
using System.Collections.Generic;
using System.Text;
using ARCam3D.Tuple;

namespace ARCam3D
{
    public class CameraProjectionTransform
    {
        private const double projectionPlaneDistance = 1;

        CameraInfo cameraInfo;
        private double horizontalFieldOfView = 0.80;
        private double verticalFieldOfView = 0.60;

        public CameraProjectionTransform(CameraInfo cameraInfo)
        {
            this.cameraInfo = cameraInfo;

            /*double d = 2 * projectionPlaneDistance * Math.Tan(cameraInfo.ViewingAngle) / 
                Math.Sqrt(cameraInfo.HorizontalResolutionPx * cameraInfo.HorizontalResolutionPx +
                    cameraInfo.VerticalResolutionPx * cameraInfo.VerticalResolutionPx);

            horizontalFieldOfView = d * cameraInfo.HorizontalResolutionPx;
            verticalFieldOfView = d * cameraInfo.VerticalResolutionPx;*/
        }

        public double HorizontalFieldOfView
        {
            get { return horizontalFieldOfView; }
        }

        public double VerticalFieldOfView
        {
            get { return verticalFieldOfView; }
        }

        public double ProjectionPlaneDistance
        {
            get { return projectionPlaneDistance; }
        }

        public Point2I GetProjection(Point3D point)
        {
            double x = point.x * projectionPlaneDistance / point.z + horizontalFieldOfView / 2;
            double y = -point.y * projectionPlaneDistance / point.z + verticalFieldOfView / 2;

            return new Point2I(
                (int) (x * cameraInfo.HorizontalResolutionPx / horizontalFieldOfView),
                (int) (y * cameraInfo.VerticalResolutionPx / verticalFieldOfView));
        }

        public Point2D GetWorldPoint(Point2I point)
        {
            return new Point2D(
                point.x * horizontalFieldOfView / cameraInfo.HorizontalResolutionPx - horizontalFieldOfView / 2,
                -point.y * verticalFieldOfView / cameraInfo.VerticalResolutionPx + verticalFieldOfView / 2
                );
        }
    }
}
